package org.lanyu.springainovel.novel.controller;

import org.lanyu.springainovel.common.dto.*;
import org.lanyu.springainovel.common.vo.RestVO;
import org.lanyu.springainovel.common.utils.TaskIdGenerator;
import org.lanyu.springainovel.novel.entity.BookAnalysisRecord;
import org.lanyu.springainovel.novel.entity.BookAnalysisResult;
import org.lanyu.springainovel.novel.service.BookAnalysisRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 拆书记录控制器（简化版API�? * 提供拆书记录的CRUD操作和任务管�? */
@RestController
@RequestMapping("/book-analysis/records")
public class BookAnalysisRecordController {

    @Autowired
    private BookAnalysisRecordService bookAnalysisRecordService;

    /**
     * 创建拆书记录并自动启动分�?     */
    @PostMapping
    public RestVO<RecordResponse> createRecord(@ModelAttribute CreateRecordRequest request) {
        try {
            BookAnalysisRecord record = new BookAnalysisRecord();
            BeanUtils.copyProperties(request, record);
            
            // 设置用户提示�?
            record.setUserPrompt(request.getUserPrompt());
            
            // 创建记录并启动分析（用户ID在服务层获取）
            BookAnalysisRecord createdRecord = bookAnalysisRecordService.createRecordAndStartAnalysis(record);
            
            // 构建响应
            RecordResponse response = new RecordResponse();
            BeanUtils.copyProperties(createdRecord, response);
            
            return RestVO.success(response);
        } catch (Exception e) {
            return RestVO.fail("创建拆书记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户的拆书记录列�?     */
    @GetMapping
    public RestVO<List<RecordResponse>> getUserRecords() {
        try {
            // 获取用户记录（用户ID在服务层获取）
            List<BookAnalysisRecord> records = bookAnalysisRecordService.getUserRecords();
            
            List<RecordResponse> responseList = records.stream().map(record -> {
                RecordResponse response = new RecordResponse();
                BeanUtils.copyProperties(record, response);
                return response;
            }).collect(Collectors.toList());
            
            return RestVO.success(responseList);
        } catch (Exception e) {
            return RestVO.fail("获取用户拆书记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取拆书记录详情
     */
    @GetMapping("/{id}")
    public RestVO<RecordResponse> getRecordById(@PathVariable Long id) {
        try {
            BookAnalysisRecord record = bookAnalysisRecordService.getRecordById(id);
            if (record == null) {
                return RestVO.fail("记录不存在");
            }
            
            RecordResponse response = new RecordResponse();
            BeanUtils.copyProperties(record, response);
            
            return RestVO.success(response);
        } catch (Exception e) {
            return RestVO.fail("获取拆书记录失败: " + e.getMessage());
        }
    }

    /**
     * 更新拆书记录
     */
    @PutMapping("/{id}")
    public RestVO<RecordResponse> updateRecord(@PathVariable Long id, @RequestBody UpdateRecordRequest request) {
        try {
            BookAnalysisRecord record = new BookAnalysisRecord();
            BeanUtils.copyProperties(request, record);
            record.setId(id);
            
            // 更新记录（权限检查在服务层进行）
            BookAnalysisRecord updatedRecord = bookAnalysisRecordService.updateRecord(record);
            
            RecordResponse response = new RecordResponse();
            BeanUtils.copyProperties(updatedRecord, response);
            
            return RestVO.success(response);
        } catch (Exception e) {
            return RestVO.fail("更新拆书记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除拆书记录
     */
    @DeleteMapping("/{id}")
    public RestVO<String> deleteRecord(@PathVariable Long id) {
        try {
            boolean success = bookAnalysisRecordService.deleteRecord(id);
            if (success) {
                return RestVO.success("删除成功");
            } else {
                return RestVO.fail("删除失败");
            }
        } catch (Exception e) {
            return RestVO.fail("删除拆书记录失败: " + e.getMessage());
        }
    }

    /**
     * 重新开始拆书分�?     */
    @PostMapping("/{id}/restart")
    public RestVO<RecordResponse> restartAnalysis(@PathVariable Long id) {
        try {
            BookAnalysisRecord record = bookAnalysisRecordService.restartAnalysis(id);
            
            RecordResponse response = new RecordResponse();
            BeanUtils.copyProperties(record, response);
            
            return RestVO.success(response);
        } catch (Exception e) {
            return RestVO.fail("重新开始拆书分析失�? " + e.getMessage());
        }
    }

    /**
     * 获取记录的状态和进度
     */
    @GetMapping("/{id}/status")
    public RestVO<BookAnalysisRecord> getRecordStatus(@PathVariable Long id) {
        try {
            BookAnalysisRecord status = bookAnalysisRecordService.getRecordStatus(id);
            return RestVO.success(status);
        } catch (Exception e) {
            return RestVO.fail("获取记录状态失�? " + e.getMessage());
        }
    }

    /**
     * 获取拆书结果
     */
    @GetMapping("/{id}/results")
    public RestVO<List<ResultResponse>> getRecordResults(@PathVariable Long id) {
        try {
            List<BookAnalysisResult> results = bookAnalysisRecordService.getRecordResults(id);
            
            List<ResultResponse> responseList = results.stream().map(result -> {
                ResultResponse response = new ResultResponse();
                BeanUtils.copyProperties(result, response);
                return response;
            }).collect(Collectors.toList());
            
            return RestVO.success(responseList);
        } catch (Exception e) {
            return RestVO.fail("获取拆书结果失败: " + e.getMessage());
        }
    }
}
